<script setup>
import { ref, reactive, watch, onMounted, h, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useIuserInfoStore, useCurrentWatchStore } from '@T2/store/users.ts';
import { workApi as MainApi, workById as MainById } from '@T2/service/api.ts';
import { downloadFiles } from '@T2/utils/utils.ts';
import { getIuserProjectRoleStr } from '@T2/utils/users.ts';
import UploadImage from '@T2/components/uploadImage/index.vue';
import UploadAttachment from '@T2/components/uploadAttachment/index.vue';

const iuserInfoStore = useIuserInfoStore();
const { info, getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['351', '352', '353']);
const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

onMounted(() => {
  GetMainTable();
});

const MainTable = reactive({
  data: [],
  total: 0,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  search: '',
  wtype: null,
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
});
const MainForm = reactive({
  model: {},
  images_json: [],
  images_updateTimes: 0,
  voices_json: [],
  voices_updateTimes: 0,
});
const MainFormRef = ref(null);
const handleMainAdd = (isAble = false) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {};
  setUserInfo(info.id);
  MainForm.images_json = [];
  MainForm.images_updateTimes++;
  MainForm.voices_json = [];
  MainForm.voices_updateTimes++;
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    wtype: row.wtype,
    describe: row.describe,
    images: row.images,
    voices: row.voices,
  };
  setUserInfo(row.user);
  MainForm.images_json = row.images_json || [];
  MainForm.images_updateTimes++;
  MainForm.voices_json = row.voices_json || [];
  MainForm.voices_updateTimes++;
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}

/* 上传资料 */
const imagesChange = (files) => {
  MainForm.model.images = files;
}
const voicesChange = (files) => {
  MainForm.model.voices = files;
}
const handleMainSubmit = () => {
  MainFormRef.value.validate((valid) => {
    if (valid) {
      MainPopup.visible = false;
      if (MainPopup.type === '新增') {
        AddMain();
      } else if (MainPopup.type === '编辑') {
        EditMain();
      }
    }
  });
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...MainForm.model,
      project: curProject.id,
      user: info.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    GetMainTable();
  });
}
const EditMain = () => {
  MainForm.model.year = +MainForm.model._year;
  delete MainForm.model._year;
  MainById({
    method: 'patch',
    id: MainForm.model.id,
    data: {
      ...MainForm.model,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    GetMainTable();
  });
}
const handleMainDelete = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 SJ-${ row.id }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

/* 详情 */
const detailPopup = reactive({
  visible: false,
  detail: null,
});
const handleDetail = (row) => {
  detailPopup.visible = true;
  detailPopup.detail = { ...row };
  setUserInfo(row.user);
}

/* 获取用户的信息 */
const iuserDetail = ref(null);
const setUserInfo = async (userID) => {
  iuserDetail.value = null;
  const { roleStr, iuserInfo } = await getIuserProjectRoleStr(userID);
  iuserDetail.value = iuserInfo;
  iuserDetail.value._roleStr = roleStr;
}
</script>

<template>
  <div class="view flex">
    <div class="work-box flex-column mainCard">
      <el-form label-width="120px" class="flex t_form">
        <el-form-item label="事件类型：">
          <el-select v-model="Filter.wtype" clearable>
            <el-option value="工作量" label="工作量"></el-option>
            <el-option value="备忘录" label="备忘录"></el-option>
            <el-option value="其他" label="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模糊查询：">
          <el-input v-model="Filter.search" clearable></el-input>
        </el-form-item>
        <div class="flex r_btn">
          <el-button type="primary" @click="handleMainAdd(RIGHT['351'])" :disabled="!RIGHT['351']">新增</el-button>
        </div>
      </el-form>
      <el-table :data="MainTable.data" scrollbar-always-on>
        <el-table-column label="序号" type="index" min-width="80px" align="center" fixed="left"></el-table-column>
        <el-table-column label="事件编号" prop="id" min-width="120px">
          <template #default="scope">
            SJ-{{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="事件类型" prop="wtype" min-width="120px"></el-table-column>
        <el-table-column label="事件描述" prop="describe" min-width="260px" show-overflow-tooltip></el-table-column>
        <el-table-column label="提交时间" prop="create_time" min-width="160px"></el-table-column>
        <el-table-column label="上报人" prop="user_name" min-width="120px"></el-table-column>
        <el-table-column label="操作" fixed="right" min-width="170px">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleMainEdit(RIGHT['352'], scope.row)" :disabled="!RIGHT['352']" v-if="scope.row.user === info.id">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleMainDelete(RIGHT['353'], scope.row)" :disabled="!RIGHT['353']">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="->, total, prev, pager, next, sizes"
        background 
        :page-sizes="[10, 20, 30, 50, 100]"
        :pager-count="5"
        v-model:currentPage="Filter.page"
        v-model:page-size="Filter.pagesize"
        :total="MainTable.total"
      />
    </div>
  </div>
  
  <!-- 新增编辑 -->
  <el-dialog width="750px" :title="MainPopup.type + '事件'" v-model="MainPopup.visible">
    <el-form
      ref="MainFormRef"
      :model="MainForm.model"
      label-width="120px"
      class="flex flex-wrap"
    >
      <template v-if="iuserDetail">
        <el-form-item class="form-col" label="上报人">
          <el-input v-model="iuserDetail.truename" disabled></el-input>
        </el-form-item>
        <el-form-item class="form-col" label="所属组织">
          <el-input v-model="iuserDetail.department_name" disabled></el-input>
        </el-form-item>
        <el-form-item class="form-col" label="角色">
          <el-input v-model="iuserDetail._roleStr" disabled></el-input>
        </el-form-item>
        <el-form-item class="form-col" label="手机号码">
          <el-input v-model="iuserDetail.contract" disabled></el-input>
        </el-form-item>
      </template>
      <el-form-item class="form-col" prop="wtype" label="事件类型：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
        <el-select v-model="MainForm.model.wtype" clearable>
          <el-option value="工作量" label="工作量"></el-option>
          <el-option value="备忘录" label="备忘录"></el-option>
          <el-option value="其他" label="其他"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="form-col" style="width: 100%;" prop="describe" label="事件描述：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input
          style="width: calc(95%);"
          v-model="MainForm.model.describe"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item class="form-col" style="width: 100%;" prop="images" label="照片">
        <UploadImage
          :files_json="MainForm.images_json"
          :updateTimes="MainForm.images_updateTimes"
          :maxSizeMB="5"
          @files-change="imagesChange"
        />
      </el-form-item>
      <el-form-item class="form-col" style="width: 50%;" prop="voices" label="音频">
        <UploadAttachment
          :fj_json="MainForm.voices_json"
          :updateTimes="MainForm.voices_updateTimes"
          :maxSizeMB="20"
          @files-change="voicesChange"
        >
          <div class="upload_info" style="margin-top: 6px">请上传音频格式文件，不超过20MB</div>
        </UploadAttachment>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="MainPopup.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleMainSubmit()">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 详情 -->
  <el-dialog width="750px" title="事件详情" v-model="detailPopup.visible">
    <div class="line flex flex-wrap" v-if="detailPopup.detail">
      <div class="info-item flex" style="width: calc(100% / 3)">
        <label>事件编号：</label>
        <p>SJ-{{ detailPopup.detail.id }}</p>
      </div>
      <template v-if="iuserDetail">
        <div class="info-item flex" style="width: calc(100% / 3)">
          <label>上报人：</label>
          <p>{{ iuserDetail.truename }}</p>
        </div>
        <div class="info-item flex" style="width: calc(100% / 3)">
          <label>所属组织：</label>
          <p>{{ iuserDetail.department_name }}</p>
        </div>
        <div class="info-item flex" style="width: calc(100% / 3)">
          <label>角色：</label>
          <p>{{ iuserDetail._roleStr }}</p>
        </div>
        <div class="info-item flex" style="width: calc(100% / 3)">
          <label>手机号码：</label>
          <p>{{ iuserDetail.contract }}</p>
        </div>
      </template>
      <div class="info-item flex" style="width: calc(100% / 3)">
        <label>提交时间：</label>
        <p>{{ detailPopup.detail.create_time }}</p>
      </div>
      <div class="info-item flex" style="width: 100%">
        <label>事件类型：</label>
        <p>{{ detailPopup.detail.wtype }}</p>
      </div>
      <div class="info-item flex" style="width: 100%">
        <label>事件描述：</label>
        <p>{{ detailPopup.detail.describe }}</p>
      </div>
      <div class="info-item flex-column" style="width: 100%" v-if="detailPopup.detail.images_json.length">
        <label>照片</label>
        <div class="images-box flex flex-wrap">
          <div class="picture-box">
            <template v-for="item in (detailPopup.detail.images_json || [])">
              <div class="image-container">
                <img :src="item.file_url" />
              </div>
            </template>
          </div>
        </div>
      </div>
      <div class="info-item flex-column" style="width: 50%" v-if="detailPopup.detail.voices_json.length">
        <label>音频</label>
        <div class="flex-column">
          <div class="voice-item flex-sb-center" v-for="item in detailPopup.detail.voices_json">
            <span class="voice-name">{{ item.name }}</span>
            <el-button type="primary" link @click="downloadFiles(item.name, item.file_url)">下载</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="detailPopup.visible = false; detailPopup.detail = null">关 闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.work-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.form-col {
  width: 50%;
  flex-direction: column;
}
/* 资料上传 */
.upload_info {
  font-size: 12px;
  color: #999999;
  line-height: 16px;
}

.line {
  width: 100%;
  .info-item {
    margin-bottom: 16px;
    label {
      font-weight: 400;
      font-size: 14px;
      color: #888888;
      white-space: nowrap;
    }
    p {
      font-weight: 400;
      font-size: 14px;
      color: #111111;
    }
  }
  .picture-box {
    flex: 1;
    display: grid;
    gap: 8px;
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
    .image-container {
      width: 80px;
      height: 80px;
      overflow: hidden;
      border-radius: 4px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        object-position: center;
      }
    }
  }
  .voice-item {
    margin-bottom: 5px;
    border-bottom: 1px solid #e6e6e6;
    .voice-name {
      font-weight: 400;
      font-size: 14px;
      color: #1890FF;
      margin-right: 20px;
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>

<style scoped>
:deep(.form-col .el-form-item__label) {
  justify-content: flex-start;
  color: #888888;
  height: 20px;
  line-height: 20px;
  margin-bottom: 4px;
}
</style>